<template>
  <base-layout
    :dialogVisible="dialogVisible"
    :dialogTitle="dialogTitle"
    @dialog-close="dialogClose"
    :visibleContent2="true"
    :visibleContent3="true"
  >
    <template #searchPanel>
      <el-form
        :inline="true"
        ref="fromdata1"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">调拨单基础信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="调拨单号:" prop="code">
              <el-input clearable readonly="readonly" v-model="fromdata.code" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调出门店:" prop="outStoreId">
              <el-select
                clearable
                class="w-100"
                v-model="fromdata.outStoreId"
                placeholder="调拨门店"
              >
                <el-option
                  v-for="item in outStoreList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storeName"
                />
              </el-select>
              <!-- <Job-shop
                v-model="fromdata.outStoreId"
                :defaultStoreId="true"
                placeholder="调出门店"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调出仓库:">
              <el-select
                clearable
                style="width: 200px"
                v-model="fromdata.outStorageId"
                placeholder="调出仓库"
              >
                <el-option
                  v-for="item in outStorageList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调拨原因:" prop="allotDescDictId">
              <el-input clearable v-model="fromdata.allotDescDictId" />
              <!-- <el-select
                clearable
                style="width: 200px"
                v-model="fromdata.allotDescDictId"
              >
                <el-option
                  v-for="item in dict['调拨原因']"
                  :key="item.index"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据时间:" prop="receiptsTime">
              <el-date-picker
                value-format="yyyy-MM-dd hh:mm:ss"
                v-model="fromdata.receiptsTime"
                type="datetime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调入门店:" prop="storeId">
              <el-input v-if="fromdata.id" disabled clearable v-model="fromdata.inStoreName" />
              <Job-shop
                v-else
                v-model="fromdata.storeId"
                disabled
                :defaultStoreId="true"
                placeholder="调入门店"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调入仓库:" prop="inStorageId">
              <el-select
                clearable
                style="width: 200px"
                v-model="fromdata.inStorageId"
                placeholder="调入仓库"
              >
                <el-option
                  v-for="item in inStorageList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="调拨备注:" prop="remark">
              <el-input
                type="textarea"
                :rows="6"
                placeholder=""
                v-model="fromdata.remark"
                style="width: 600px"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
        class="insuranceForm"
      >
        <el-row>
          <el-col :span="12">调拨负责人员</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="管理人员:" prop="userName" label-width="120px">
              <el-input
                clearable
                v-model.number="fromdata.userName"
                @focus="employeeFocus"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话:" prop="phone" label-width="120px">
              <el-input clearable v-model.number="fromdata.phone" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel2>
      <el-form
        :inline="true"
        ref="fromdata"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
        class="insuranceForm"
      >
        <el-row>
          <el-col :span="22">调拨配件列表</el-col>
          <el-col :span="2">
            <el-button icon="el-icon-plus" type="primary" @click="addInventory"
              >添加调拨出库配件</el-button
            >
          </el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <data-table
            :value="fromdata.partsList"
            :total-count="totalCount"
            :has-action="true"
            :table-column-attributes="tableColumnAttributes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :width="160"
            :localPage="true"
          >
            <template #action="{ row }">
              <i
                class="el-icon-delete"
                title="删除"
                style="color: red; margin-left: 20px; cursor: pointer"
                @click="deleteLochost(row)"
              ></i>
            </template>
            <template #allNum>
              <el-col :span="8" v-if="allMount">
                <span style="line-height: 10px; text-align: left; color: #606266"
                  >调拨配件总金额：<span style="color: #f40; font-size: 20px"
                    >￥{{ allMount }}</span
                  ></span
                >
              </el-col>
              <el-col :span="8" v-if="allMount1">
                <span style="line-height: 10px; text-align: left; color: #606266"
                  >调拨配件总数：<span style="color: #f40; font-size: 20px">{{
                    allMount1
                  }}</span></span
                >
              </el-col>
            </template>
          </data-table>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel3>
      <el-row>
        <el-col :span="24" align="right" justify="center">
          <el-col :span="24">
            <span style="line-height: 10px; text-align: left; color: #606266"
              >出库总金额：<span style="color: #f40; font-size: 20px" v-if="allMount"
                >￥{{ allMount }}</span
              ></span
            >
          </el-col>
          <el-col :span="24" style="margin-top: 20px">
            <el-button type="success" @click="saveUpdate">新建调拨单</el-button>
          </el-col>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <SelectAccessories
        :storageId="fromdata.outStoreId"
        v-if="showSelect"
        @partsList="partsList"
      />
      <EmployeeTable
        v-if="showEmployeeTable"
        @roleIdListSelectCheck="employeListSelectCheck"
        :checkList="[fromdata.manageUserName]"
      />
    </template>
  </base-layout>
</template>
<script>
import baseMixin from "@/mixins/base";
import { findByStore } from "@/api/after-sale/storehouseManage/warehouseManage";
import { getDict, parseTimeToYMDHMS } from "@/utils";
import SelectAccessories from "@/components/SelectAccessories/index"; //导入组件
import EmployeeTable from "../../systemManage/store/components/EmployeeTable";
import {
  add,
  update,
  getAllotCode,
  getFindById,
  getAllStore,
} from "@/api/after-sale/storehouseManage/transferManage";
import {
  findByStoreIdAndStorageId,
  getDetail as getFindPosDetail,
} from "@/api/after-sale/storehouseManage/positionManage";
import store from "@/store";
export default {
  components: {
    SelectAccessories,
    EmployeeTable,
  },
  mixins: [
    baseMixin({
      addData: add,
      updateData: update,
      format(res) {
        return res.map((data) => {
          return data;
        });
      },
    }),
  ],
  watch: {
    "fromdata.storeId": function (value) {
      if (value) {
        this.getInWareHouse(value);
      } else {
        this.getInWareHouse(store.state.user.entryStore);
      }
    },
    "fromdata.outStoreId": function (value) {
      if (value) {
        this.getOutWareHouse(value);
      } else {
        this.getOutWareHouse(store.state.user.entryStore);
      }
    },
    "fromdata.outStorageId": function (value) {
      if (value) {
        this.findByStoreIdAndStorageId(this.fromdata.outStoreId, value);
      }
    },
    "fromdata.partsList": {
      handler(value) {
        this.sumAllMount();
      },
      deep: true,
    },
  },
  data() {
    return {
      fromdata: { partsList: [], id: "", receiptsTime: parseTimeToYMDHMS(new Date()) },
      rules: {
        receiptsTime: [{ required: true, message: "请选择单据日期", trigger: "change" }],
        outStoreId: [{ required: true, message: "请选择调出门店", trigger: "change" }],
        storeId: [{ required: true, message: "请选择调入门店", trigger: "change" }],
        inStorageId: [{ required: true, message: "请选择调入仓库", trigger: "change" }],
        allotDescDictId: [
          { required: true, message: "请选择调拨原因", trigger: "change" },
        ],
      },
      dict: [],
      outStorageList: [],
      inStorageList: [],
      outStoreList: [], // 调出所有门店
      showSelect: false, // 是否展示配件组件
      showEmployeeTable: false, //  是否展示员工组件
      allMount: null,
      allMount1: null,
      tableColumnAttributes: [
        { name: "配件编号", value: "partsCode", type: "text" },
        { name: "配件名称", value: "partsName", type: "text" },
        { name: "配件类别", value: "partsType", type: "text" },
        { name: "配件单位", value: "partsUnit", type: "text" },
        {
          name: "配件仓位",
          filterable: true,
          value: "storageSiteName",
          type: "select",
          valueId: "outStorageSiteId",
          action: this.storageSiteChange,
          options: this.findByStoreIdAndStorageId,
        },
        { name: "仓位编号", value: "storageSiteCode", type: "text" },
        {
          name: "出库数量",
          value: "num",
          type: "inputNumber",
          action: function (row) {
            row.amount = row.num * row.storagePrice;
          },
        },
        { name: "出库内置数", value: "internalNum", type: "text" },
        { name: "仓位剩余", value: "alreadyNum", type: "text" },
        { name: "采购成本", value: "purchasePrice", type: "text" },
        { name: "销售价", value: "storagePrice", type: "text" },
        {
          name: "出库单价",
          value: "outStoragePrice",
          type: "input",
          widht: "100px",
        },
        { name: "总金额", value: "amount", type: "text" },
      ],
    };
  },
  methods: {
    // 动态计算表格总和
    sumAllMount() {
      this.allMount = null;
      this.allMount1 = null;
      this.fromdata.partsList.forEach((e) => {
        if (e.amount) {
          this.allMount += Number.parseFloat(e.amount);
        }
        if (e.num) {
          this.allMount1 += Number.parseInt(e.num);
        }
      });
    },
    // 获取仓位信息
    async findByStoreIdAndStorageId(storeId, storageId) {
      let { data } = await findByStoreIdAndStorageId(storeId, storageId);
      data.forEach((e) => {
        e.value = e.storageSiteName;
      });
      this.tableColumnAttributes[4].options = data;
      this.positionList = data;
    },
    async storageSiteChange(row) {
      getFindPosDetail(row.outStorageSiteId).then((res) => {
        let { data } = res;
        for (let i in this.fromdata.partsList) {
          if (this.fromdata.partsList[i].id === row.id) {
            // this.$set(this.fromdata.partsList[i], "alreadyNum", data.alreadyNum);
            this.$set(
              this.fromdata.partsList[i],
              "storageSiteCode",
              data.storageSiteCode
            );
          }
        }
      });
    },
    // 获取调入仓库
    async getInWareHouse(id) {
      let { data } = await findByStore(id);
      this.inStorageList = data;
    },
    // 获取调出仓库
    async getOutWareHouse(id) {
      let { data } = await findByStore(id);
      this.outStorageList = data;
    },
    // 打开配件选择
    addInventory() {
      this.showSelect = true;
      this.showEmployeeTable = false;
      this.handleDataInsert("配件选择");
    },
    //删除临时配件
    deleteLochost(row) {
      this.fromdata.partsList = this.fromdata.partsList.filter((e) => e.id != row.id);
    },
    //打开员工选择列表
    employeeFocus() {
      this.showSelect = false;
      this.showEmployeeTable = true;
      this.handleDataInsert("管理人员列表");
    },
    //员工选择
    employeListSelectCheck(select) {
      this.fromdata.userName = select[0].userName;
      this.fromdata.phone = select[0].phone;
      this.fromdata.userId = select[0].id;
      this.dialogClose();
    },
    // 选择配件
    partsList(value) {
      if (value.length > 0) {
        value.forEach((e) => {
          let index = true;
          this.fromdata.partsList.forEach((g) => {
            if (e.id === g.id) {
              index = false;
            }
          });
          if (index) {
            let { ...data } = {
              ...e,
              partsUnit: e.unit,
              partsId: e.id,
              partsType: e.partsDictValue,
            };
            this.fromdata.partsList.push(data);
          }
        });
      }
      this.dialogClose();
    },
    saveUpdate() {
      this.$refs["fromdata1"].validate((valid) => {
        if (valid) {
          this.handleDataUpdate(this.fromdata);
          this.closeRouter();
        }
      });
    },
    async detail(id) {
      let { data } = await getFindById(id);
      this.fromdata = data;
    },
    async getAllotCode() {
      let { data } = await getAllotCode();
      this.fromdata.code = data;
    },
    async getAllStore() {
      let { data } = await getAllStore();
      this.outStoreList = data;
    },
  },
  mounted() {
    this.dict = getDict(["调拨原因"]);
    this.getInWareHouse(store.state.user.entryStore);
    this.getOutWareHouse(store.state.user.entryStore);
    let id = this.$route.query.id;
    this.getAllStore();
    if (id) {
      this.fromdata.id = id;
      this.detail(id);
    } else {
      this.getAllotCode();
    }
  },
};
</script>
<style lang="scss" scoped></style>
